package org.qengine.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.qengine.dao.*;
import org.qengine.entity.DSelLevelEntity;
import org.qengine.entity.PaperRulesEntity;
import org.qengine.entity.QuestionEntity;
import org.qengine.service.PaperRulesService;
import org.qengine.vo.PaperRulesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@Service("paperRulesService")
public class PaperRulesServiceImpl extends ServiceImpl<PaperRulesDao, PaperRulesEntity>
        implements PaperRulesService {
    @Autowired
    public PaperRulesDao paperRulesDao;
    @Autowired
    public QuestionDao questionDao;
    @Autowired
    public KnowledgeSelIdDao knowledgeSelDao;
    @Autowired
    public ProblemSelTypeDao problemSelTypeDao;
    @Autowired
    public DSelLevelDao dSelLevelDao;
    @Override
    // 根据 ruleID 查询规则
    public PaperRulesEntity getPaperRules(Long ruleId) {
        LambdaQueryWrapper<PaperRulesEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperRulesEntity::getRuleId, ruleId);
        // 调用父类的getOne方法来查询单个实体
        return getOne(wrapper);
    }

    @Override
    //增加与更新规则
    public String savePaperRules(PaperRulesVo paperRulesVo) {
        // 将 Vo 转换为 Entity
        PaperRulesEntity entity = convertVoToEntity(paperRulesVo);
        // 判断是新增还是更新
        if (entity.getRuleId() != null) {
            // 根据 ruleID 查询数据库
            PaperRulesEntity existingEntity = this.getById(entity.getRuleId());
            if (existingEntity != null) {
                // 如果存在，则更新
                this.updateById(entity);
                return "成功更新了一条原有的记录";
            } else {
                // 如果不存在，则新增
                this.save(entity);
                return "成功新增了一条记录";
            }
        } else {
            // 如果 ruleID 为 null，返回错误信息

            return "ruleID 不能为 null";
        }
    }


    public PaperRulesEntity convertVoToEntity(PaperRulesVo paperRulesVo) {
        // 创建 PaperRulesEntity 对象
        PaperRulesEntity entity = new PaperRulesEntity();

        // 将 Vo 中的字段值赋给 Entity
        entity.setRuleId(paperRulesVo.getRuleId());
        entity.setCourseId(paperRulesVo.getCourseId());
        entity.setKnowledgeSelId(paperRulesVo.getKnowledgeSelId());
        entity.setDSelLevel(paperRulesVo.getDSelLevel());
        entity.setProblemSelType(paperRulesVo.getProblemSelType());

        // 返回转换后的 Entity 对象
        return entity;
    }

    @Override
    // 删除规则
    public String delPaperRules(PaperRulesEntity entity) {

        if (entity.getRuleId() != null) {
            // 根据 ruleID 查询数据库
            PaperRulesEntity existingEntity = this.getById(entity.getRuleId());
            if (existingEntity != null) {
                // 如果存在，则删除
                this.removeById(entity.getRuleId());
                return "成功删除了一条原有的记录";
            } else {
                // 如果不存在，则返回错误信息
                return "要删除的记录不存在";
            }
        } else {
            // 如果 ruleID 为 null，返回错误信息
            return "ruleID 不能为 null";
        }
    }

    @Override

    public IPage<PaperRulesEntity> findPaperRulesByConditions(Long courseId, Long knowledgeSelId, Long problemSelType, Long dSelLevel, int current, int size) {
        Page<PaperRulesEntity> page = new Page<>(current, size);
        return paperRulesDao.findByConditions(
                page, courseId, knowledgeSelId, problemSelType, dSelLevel);
    }

    @Override
    public IPage<PaperRulesEntity> getPaperRulesPage(int current, int size) {

        Page<PaperRulesEntity> page = new Page<>(current, size);
        return paperRulesDao.selectPage(page, null);

    }

    @Override
    public List<QuestionEntity> GeneratePaper(Long ruleId) {
        Random rand = new Random();
        int check=0;
        PaperRulesEntity paperRulesEntity = this.getPaperRules(ruleId);
        List<QuestionEntity> result = new ArrayList<>();
        if (paperRulesEntity!= null) {
            int course = paperRulesEntity.getCourseId().intValue();
            QuestionEntity questionEntity = new QuestionEntity();
            int[] typeNum = new int[4];
            typeNum[0] = (int) (10 * problemSelTypeDao.findByIdInPro(paperRulesEntity.getProblemSelType()).getType1());
            typeNum[1] = (int) (10 * problemSelTypeDao.findByIdInPro(paperRulesEntity.getProblemSelType()).getType2());
            typeNum[2] = (int) (10 * problemSelTypeDao.findByIdInPro(paperRulesEntity.getProblemSelType()).getType3());
            typeNum[3] = (int) (10 * problemSelTypeDao.findByIdInPro(paperRulesEntity.getProblemSelType()).getType4());
            int check1 = typeNum[0] + typeNum[1] + typeNum[2] + typeNum[3] - 10;
            if (check1 > 0) {
                typeNum[findMaxIndex(typeNum)] -= check1;
            }
            if (check1 < 0) {
                typeNum[findMinIndex(typeNum)] += check1;
            }
            int[] levelNum = new int[4];
            levelNum[0] = (int) (10 * dSelLevelDao.findByIdInDL(paperRulesEntity.getDSelLevel()).getDLevel1());
            levelNum[1] = (int) (10 * dSelLevelDao.findByIdInDL(paperRulesEntity.getDSelLevel()).getDLevel2());
            levelNum[2] = (int) (10 * dSelLevelDao.findByIdInDL(paperRulesEntity.getDSelLevel()).getDLevel3());
            levelNum[3] = (int) (10 * dSelLevelDao.findByIdInDL(paperRulesEntity.getDSelLevel()).getDLevel4());
            int check2 = levelNum[0] + levelNum[1] + levelNum[2] + levelNum[3] - 10;
            if (check2 > 0) {
                levelNum[findMaxIndex(levelNum)] -= check2;
            }
            if (check2 < 0) {
                levelNum[findMinIndex(levelNum)] += check2;
            }

            int[] delNum = new int[5];
            delNum[0] = (knowledgeSelDao.findByIdInKN(paperRulesEntity.getKnowledgeSelId()).getId1()).intValue();
            delNum[1] = (knowledgeSelDao.findByIdInKN(paperRulesEntity.getKnowledgeSelId()).getId2()).intValue();
            delNum[2] = (knowledgeSelDao.findByIdInKN(paperRulesEntity.getKnowledgeSelId()).getId3()).intValue();
            delNum[3] = (knowledgeSelDao.findByIdInKN(paperRulesEntity.getKnowledgeSelId()).getId4()).intValue();
            delNum[4] = (knowledgeSelDao.findByIdInKN(paperRulesEntity.getKnowledgeSelId()).getId5()).intValue();
            int check3 = delNum[0] + delNum[1] + delNum[2] + delNum[3] + delNum[4] - 10;
            if (check3 > 0) {
                levelNum[findMaxIndex(levelNum)] -= check3;
            }
            if (check3 < 0) {
                levelNum[findMinIndex(levelNum)] += check3;
            }
            while (allZeros(delNum) && allZeros(levelNum) && allZeros(typeNum)) {
                check++;
                if (check > 100) {
                    break;}
                int a = findMaxIndex(typeNum);
                int b = findMaxIndex(levelNum);
                int c = findMaxIndex(delNum);
                List<QuestionEntity> ate = questionDao.selectQuestionByTrainingPaperRules(2, 1, 2, 3);
                QuestionEntity addQuestion = questionDao.selectQuestionByTrainingPaperRules(typeNum[a], course, delNum[c], levelNum[b]).stream().findAny().orElse(null);
                if (addQuestion != null) {
                    result.add(addQuestion);
                    typeNum[a]--;
                    levelNum[b]--;
                    delNum[c]--;
                } else {

                    a = rand.nextInt(4);
                    b = rand.nextInt(4);
                    c = rand.nextInt(5);
                    addQuestion = questionDao.selectQuestionByTrainingPaperRules(typeNum[a], course, delNum[c], levelNum[b]).stream().findAny().orElse(null);
                    if (addQuestion != null) {
                        result.add(addQuestion);
                        typeNum[a]--;
                        levelNum[b]--;
                        delNum[c]--;
                    }
                }
            }
        }  return result;
    }
    public static int findMaxIndex(int[] array) {
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException("数组不能为空");
        }

        int maxIndex = 0; // 假设第一个元素是最大值
        for (int i = 1; i < array.length; i++) {
            if (array[i] > array[maxIndex]) {
                maxIndex = i; // 更新最大值的索引
            }
        }
        return maxIndex;
    }
    public static int findMinIndex(int[] array) {
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException("数组不能为空");
        }

        int minIndex = 0; // 假设第一个元素是最大值
        for (int i = 1; i < array.length; i++) {
            if (array[i] < array[minIndex]) {
                minIndex = i; // 更新最大值的索引
            }
        }
        return minIndex;
    }
    public static boolean allZeros(int[] arr) {
        for (int element : arr) {
            if (element != 0) {
                return true;
            }
        }
        return false;
    }
    public List<QuestionEntity> getWrongQuestions() {
        return questionDao.findWrongQuestions();
    }

}
